package com.mxy.myapplication2.kotlin

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View

/**
 * 自定义View
 */
class MyView : View {

    constructor(context: Context) : super(context) {

    }

    constructor(context: Context, AttributeSet: AttributeSet) : super(context, AttributeSet) {

    }

    /**
     * @param defaultSize UI控件默认尺寸
     * @param heightMeasureSpec UI 控件测量模式
     *
     * 测量模式分为三种
     * MeasureSpec.AT_MOST=wrap_content
     * MeasureSpec.EXACTLY=具体数值||match_parent
     * MeasureSpec.UNSPECIFIED
     *
     * */
    fun getMyViewSize(defaultSize: Int, measureSpec: Int): Int {

        var viewSize: Int = defaultSize

        val mode: Int = MeasureSpec.getMode(measureSpec)
        val size: Int = MeasureSpec.getSize(measureSpec)

        when (mode) {
            MeasureSpec.AT_MOST -> {
                viewSize = size
            }
            MeasureSpec.EXACTLY -> {
                viewSize = size
            }
            MeasureSpec.UNSPECIFIED -> {
                viewSize = defaultSize
            }
        }

        return viewSize
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        var viewWidth: Int = getMyViewSize(100, widthMeasureSpec);
        var viewHeight: Int = getMyViewSize(100, heightMeasureSpec)

        //获取手动设定的高度，如果所在父布局(RelativeLayout)高度很大，那么heightMeasureSpec会首先测量父布局的高度，造成测量错误
        if (viewHeight > layoutParams.height) {
            viewHeight = layoutParams.height
        }

        //正方形的View
        if (viewWidth != viewHeight) {
            viewWidth = viewHeight
        }
        setMeasuredDimension(viewWidth, viewHeight);
    }


    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        val circularRaduis : Int = layoutParams.height/2

        val paint = Paint()
        paint.color=Color.GREEN

        canvas?.drawCircle(circularRaduis+0F,circularRaduis+0F,circularRaduis+0F,paint)

    }
}